//
//  AdoptedSelectTrusteeViewController.m
//  PigMarket
//
//  Created by mac on 2019/5/14.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "AdoptedSelectTrusteeViewController.h"
#import "BuyPigCell.h"
#import "PigPayFooterView.h"
#import "AdoptedPayViewController.h"
#import "PigTrusteePriceView.h"
#import "AdoptedTrusteeView.h"
#import "SelectDiscountCouponsView.h"

#import "AdoptedNewPayViewController.h"

#define kOrderMoney @"99"
@interface AdoptedSelectTrusteeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic , strong) UITableView *myTableView;
@property (nonatomic , strong) NSArray *leftTitleArr;
@property (nonatomic , strong) NSDictionary *footerInfoDic;
@property (nonatomic , strong) SelectDiscountCouponsView *selectCouponsView;
@property (nonatomic , strong) NSMutableArray *trusteeArr;
@property (nonatomic , strong) NSString *selectTrusteePrice;
@property (nonatomic , strong) NSString *pigPrice;
@property (nonatomic , strong) PigPayFooterView *footerView;
@property (nonatomic , strong) NSString *owedPaymentMoney;
@property (nonatomic , strong) NSString *actuallyPaymentMoney;
@property (nonatomic , strong) NSString *discountMoney;
@property (nonatomic , strong) NSString *discountTips;
@property (nonatomic , strong) NSMutableArray *discountCouposArr;
@property (nonatomic , strong) NSMutableArray *discountCouposIdArr;

@end

@implementation AdoptedSelectTrusteeViewController


#pragma mark - view life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.baseNavView.navTitleLabel.text = @"支付";
    [self setUpView];
}

#pragma mark - init method
- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}


- (void)initView {
    [self.view addSubview:self.myTableView];
}

- (void) initLayout {
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(TJ_NavBarHeight, 0, 0, 0));
    }];
}

- (void) initAction {

    [kNotificationCenter addObserver:self selector:@selector(selectTrusteePriceNot:) name:NotificationTrusteePriceChange object:nil];
    //选择豚券 确定回调
    @weakify(self);
    [self.selectCouponsView setSelectedDiscountCouponsBlock:^(int selectMoney, NSMutableArray *discountCouponIdArr) {
        
        @strongify(self);
        if (selectMoney == 0) {
            self.discountTips = [NSString stringWithFormat:@"￥%d",selectMoney];
        } else {
            self.discountTips = [NSString stringWithFormat:@"￥-%d",selectMoney];
        }
        self.discountMoney = [NSString stringWithFormat:@"%d",selectMoney];
        [self.discountCouposIdArr addObjectsFromArray:discountCouponIdArr];
        
        [self.selectCouponsView removeFromSuperview];
        [self refreshData];
        [self.myTableView reloadData];
    }];
}


- (void)initData {
    
    //获取豚券
    [self discountCouponsRequest];
   

    //数据请求
    [self dataRequest];
    
    //加载固定数据
    [self refreshData];

}


- (void)refreshData {

    NSString *orderPrice = @"0";
    //取出小猪的价钱
    NSNumber *pigPrice = @(0);
    switch (self.adoptType) {
        case AdoptedTypeBuy://直接购买后，再次交托管费用的情况
        {
             //应付款 = 托管费用
            self.owedPaymentMoney = self.selectTrusteePrice;
            
            //实付款 = 阶段费用 - 豚券
            self.actuallyPaymentMoney = [NSString stringWithFormat:@"%.2f",[self.owedPaymentMoney floatValue]  - [self.discountMoney floatValue]];
            
          }
            break;
        case AdoptedTypeFree://免费试养  交托管费用
        {
            //取出小猪的价钱
            if (self.trusteeArr.count > 0) {
                AdoptedTrustee *model = self.trusteeArr[0];
                pigPrice = model.money;
            }

            //应付款 = 猪的价钱 + 阶段费用
            self.owedPaymentMoney = [NSString stringWithFormat:@"%.2f",[pigPrice floatValue] + [self.selectTrusteePrice floatValue]];
            
            //实付款 = 应付价钱 - 豚券
            self.actuallyPaymentMoney = [NSString stringWithFormat:@"%.2f",[self.owedPaymentMoney floatValue] - [self.discountMoney floatValue]];
            
        }
            break;
        case AdoptedTypeOrder://99预定 交托管费用
        {
            orderPrice = kOrderMoney;
            
            //取出小猪的单价

            if (self.trusteeArr.count > 0) {
                AdoptedTrustee *model = self.trusteeArr[0];
                pigPrice = model.money;
            }
          
           
            //应付款 = selectTrusteePrice
            self.owedPaymentMoney = [NSString stringWithFormat:@"%.2f",[pigPrice floatValue] + [self.selectTrusteePrice floatValue]];

            //实付款 = 应付价钱 - 豚券 - 99
            self.actuallyPaymentMoney = [NSString stringWithFormat:@"%.2f",[self.owedPaymentMoney floatValue] - [orderPrice floatValue] - [self.discountMoney floatValue]];

         }
            break;
        default:
            break;
    }
    //本次所选阶段费用
    NSString *selectedPrice = [NSString stringWithFormat:@"￥%@",self.selectTrusteePrice ? self.selectTrusteePrice : @"0"];
    NSString *pigPriceDetail = [NSString stringWithFormat:@"￥%@",pigPrice];
    self.discountTips = self.discountTips ? self.discountTips : @"";

    if (self.adoptType == AdoptedTypeBuy) {
        self.leftTitleArr = @[@[@{@"icon":@"",@"title":@"托管阶段",@"tips":@"可多选"},
                                @{@"icon":@"",@"title":@"",@"tips":@""}],
                              @[@{@"icon":@"",@"title":@"结算信息",@"tips":@""},
                                @{@"icon":@"",@"title":@"本次所选阶段费用",@"tips":@"",@"detail":selectedPrice},
                                @{@"icon":@"adopt_adoptdetail_coupon",@"title":@"豚券",@"tips":@"",@"detail":self.discountTips}]];
        

    } else if (self.adoptType == AdoptedTypeOrder){
        NSString *orderStr = [NSString stringWithFormat:@"-￥%@",orderPrice];

        self.leftTitleArr = @[@[@{@"icon":@"",@"title":@"托管阶段",@"tips":@"可多选"},
                                @{@"icon":@"",@"title":@"",@"tips":@""}],
                              @[@{@"icon":@"",@"title":@"结算信息",@"tips":@""},
                                @{@"icon":@"",@"title":@"仔猪价格",@"tips":@"",@"detail":pigPriceDetail},
                                @{@"icon":@"",@"title":@"本次所选阶段费用",@"tips":@"",@"detail":selectedPrice},
                                @{@"icon":@"",@"title":@"定金",@"tips":@"",@"detail":orderStr},
                                @{@"icon":@"adopt_adoptdetail_coupon",@"title":@"豚券",@"tips":@"",@"detail":self.discountTips}]];
        

    } else if (self.adoptType == AdoptedTypeFree){
        self.leftTitleArr = @[@[@{@"icon":@"",@"title":@"托管阶段",@"tips":@"可多选"},
                                @{@"icon":@"",@"title":@"",@"tips":@""}],
                              @[@{@"icon":@"",@"title":@"结算信息",@"tips":@""},
                                @{@"icon":@"",@"title":@"仔猪价格",@"tips":@"",@"detail":pigPriceDetail},
                                @{@"icon":@"",@"title":@"本次所选阶段费用",@"tips":@"",@"detail":selectedPrice},
                                @{@"icon":@"adopt_adoptdetail_coupon",@"title":@"豚券",@"tips":@"",@"detail":self.discountTips}]];

    }
    //优惠价钱
    if ([JTool iSNull:self.discountMoney]) {//如果为空 默认赋值为0
        self.discountMoney = @"0";
    }

    NSString *discount = [NSString stringWithFormat:@"(已优惠%@元)",self.discountMoney];
    self.footerInfoDic = @{@"title":@"实付款",
                           @"discount":discount,
                           @"confirmTitle":@"立即支付"
                           };
    
    self.footerView.infoDic = self.footerInfoDic;
    if ([self.actuallyPaymentMoney intValue] < 0 || [JTool iSNull:self.actuallyPaymentMoney]) {
        self.actuallyPaymentMoney = [NSString stringWithFormat:@"%.2f",0.00];
    }
    self.footerView.priceLab.text = [NSString stringWithFormat:@"￥%@",self.actuallyPaymentMoney];
}


#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    }else {
        if (self.leftTitleArr.count > 0) {
            return [self.leftTitleArr[1] count];
        }
    }
    return 0;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 1) {
        return 54;
    }else {
        return 0.01;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return [[UIView alloc] init];
    }else {
        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
        [footerView addSubview:_footerView];
        return footerView;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 1) {
        int count = (int)self.trusteeArr.count / 3;
        if (self.trusteeArr.count % 3 > 0) {
            count += 1;
        }
        return 120 * count + 50;
    }else {
        return 50;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 1) {
        TrusteeCell *cell = [TrusteeCell cellWithTrusteeTableView:tableView];
        [cell configCellWithDataArr:self.trusteeArr type:TrusteeTypeAdopted];
        return cell;
    }else {
        BuyPigCell *cell = [BuyPigCell cellWithTableView:tableView];
        
        [cell configCellWithLeftTitleDic:self.leftTitleArr[indexPath.section][indexPath.row] indexPath:indexPath];
        NSUInteger count = [self.leftTitleArr[1] count];
        if (indexPath.section == 1 && indexPath.row == count - 1) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        return cell;
    }
    return nil;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dic = self.leftTitleArr[indexPath.section][indexPath.row];
    if ([dic[@"title"] isEqualToString:@"豚券"]) {
        if (self.discountCouposArr.count == 0) {
            [self toastWithContent:@"您无可用豚券"];
            return;
        } else {
            self.selectCouponsView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
            self.selectCouponsView.dataArr = self.discountCouposArr;
            [[UIApplication sharedApplication].keyWindow addSubview:self.selectCouponsView];
        }
    }
}


#pragma mark - target action
//接收通知  套餐选择价钱套餐  刷新页面价钱
- (void)selectTrusteePriceNot: (NSNotification *)notification {
    NSDictionary *dic = notification.userInfo;
    self.selectTrusteePrice = [NSString stringWithFormat:@"%@",dic[@"selectTrusteePrice"]];
    
    NSLog(@"___________    %@", self.selectTrusteePrice);
    [self refreshData];
    [self.myTableView reloadData];
}


//立即支付
- (void)payTapped {

    //是否缴纳了托管所有费用
    BOOL isPayAllMoney = YES;

    //所选套餐idArr
    NSMutableArray *trustIdArr = [[NSMutableArray alloc] init];
    for (AdoptedTrustee *model in self.trusteeArr) {
        if ([model.type intValue]== 1) {//阶段套餐 （仔猪和全包不用传id）
            if (model.isSelect) {
                [trustIdArr addObject:model.trustId];

            }
        }
    }

    //判断是否全缴纳了托管费用
    for (AdoptedTrustee *model in self.trusteeArr) {
        if ([model.type intValue]== 1) {
            if ([model.status intValue] == 0) {//没交
                isPayAllMoney = NO;
                break;
            }
        }
    }

    if (isPayAllMoney) {
        [self toastWithContent:@"您已缴纳全部托管费用"];
        return;
    }
    //添加套餐
    if (!([self.selectTrusteePrice floatValue] > 0)) {
        [self toastWithContent:@"请选择阶段托管费用"];
        return;
    }
    AdoptedNewPayViewController *vc = [[AdoptedNewPayViewController alloc] init];
    vc.actuallyPaymentMoney = self.actuallyPaymentMoney;//实付款
    vc.discountMoney = self.discountMoney;

    //(后台要求 99预定界面  应付金额 =  应付金额 - 99)
    if (self.adoptType == AdoptedTypeOrder) {
        NSString *owedPaymentMoney = [NSString stringWithFormat:@"%.2f",[self.owedPaymentMoney floatValue] - [kOrderMoney floatValue]];
        vc.owedPaymentMoney = owedPaymentMoney;
    } else {
        vc.owedPaymentMoney = self.owedPaymentMoney;
    }

    vc.adoptPlanId = self.adoptPlanId;
    vc.model = self.model;
    vc.trusteeIdArr = trustIdArr;
    vc.discountMoney = self.discountMoney;
    vc.discountMoneyIdArr = self.discountCouposIdArr;

    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - private method
//获取豚券请求
- (void)discountCouponsRequest {
    
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    DiscountCouponsParam *param = [[DiscountCouponsParam alloc] init];
    param.page = 1;;
    param.limit = 50;
    param.memberId = memberId;
    param.type = @1;
    @weakify(self);
    [[[PigMarketApi sharedInstance] userDiscountCouponsWithParam:param] subscribeNext:^(DiscountCouponsList * _Nullable discountCouponsList) {
        @strongify(self);
        
        [self.discountCouposArr addObjectsFromArray:discountCouponsList.list];
        
        if (self.discountCouposArr.count == 0) {
            self.discountTips = @"无可用豚券";
        } else {
            self.discountTips = @"有可用豚券";
        }
        [self refreshData];
        [self.myTableView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


//数据请求
- (void)dataRequest {
    @weakify(self);
    [[[PigMarketApi sharedInstance] adoptedTrusteeWithAdoptPlanId:self.adoptPlanId] subscribeNext:^(AdoptedTrusteeList * _Nullable trusteeList) {
        @strongify(self);
        
        
        [self.trusteeArr addObjectsFromArray:trusteeList.list];
        [self.myTableView reloadData];
        [self refreshData];
    } error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
    }];
}


#pragma mark - getter and setter
- (UITableView *)myTableView {
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableView.rowHeight = 42;
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
    }
    return _myTableView;
}


- (NSArray *)leftTitleArr {
    if (!_leftTitleArr) {
        _leftTitleArr = [[NSArray alloc] init];
    }
    return _leftTitleArr;
}


- (NSMutableArray *)trusteeArr {
    if (!_trusteeArr) {
        _trusteeArr = [[NSMutableArray alloc] init];
    }
    return _trusteeArr;
}


- (PigPayFooterView *)footerView {
    if (!_footerView) {
        _footerView = [[PigPayFooterView alloc] init];
        [_footerView.confirmBtn addTarget:self action:@selector(payTapped) forControlEvents:UIControlEventTouchUpInside];
        _footerView.backgroundColor = [UIColor whiteColor];
        _footerView.frame = CGRectMake(0, 10, SCREEN_WIDTH, 54);
    }
    return _footerView;
}


- (SelectDiscountCouponsView *)selectCouponsView {
    if (!_selectCouponsView) {
        _selectCouponsView = [[SelectDiscountCouponsView alloc] init];
    }
    return _selectCouponsView;
}


- (NSMutableArray *)discountCouposArr {
    if (!_discountCouposArr) {
        _discountCouposArr = [[NSMutableArray alloc] init];
    }
    return _discountCouposArr;
}


- (NSMutableArray *)discountCouposIdArr {
    if (!_discountCouposIdArr) {
        _discountCouposIdArr = [[NSMutableArray alloc] init];
    }
    return _discountCouposIdArr;
}


@end
